package com.easytouch.vmhdl.fragment;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easytouch.core.Configure;
import com.easytouch.core.DriverThread;
import com.easytouch.core.model.ColumnModel;
import com.easytouch.core.model.GoodsModel;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.Tools;
import com.easytouch.vmhdl.AppApplication;
import com.easytouch.vmhdl.R;
import com.easytouch.vmhdl.activity.ManagerActivity;
import com.easytouch.vmhdl.interfaces.IManagerAddView;
import com.easytouch.vmhdl.model.ManagerAddModel;
import com.easytouch.vmhdl.presenter.ManagerAddPresenter;
import com.easytouch.vmhdl.view.LongClickButton;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gulin on 2018/1/12.
 */

public class AddFragment extends BaseMgrFragment implements View.OnClickListener, IManagerAddView {

    private ManagerAddPresenter mPresenter;
    private ManagerAddAdapter mAdapter;

    private List<ColumnModel> mList = new ArrayList<>();
    private int mBox = 0;
    private GridView mGrid;
    private LinearLayout mLlTop;
    private int mGoodsPrice = 0;

    private ProgressDialog mProgressDialog;

    private Log mLogger = new Log("AddFragment.txt");

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add, container, false);
        setTitle(R.string.mgr_add_title);

        mLlTop = view.findViewById(R.id.ll_top);
        mGrid = view.findViewById(R.id.gv_add);

        Button btAddOne = view.findViewById(R.id.bt_add_one);
        btAddOne.setOnClickListener(this);
        Button btAddAll = view.findViewById(R.id.bt_add_all);
        btAddAll.setOnClickListener(this);
        Button btImport = view.findViewById(R.id.bt_import);
        btImport.setOnClickListener(this);
        Button btExport = view.findViewById(R.id.bt_export);
        btExport.setOnClickListener(this);
        Button btBack = view.findViewById(R.id.bt_back);
        btBack.setOnClickListener(this);

        mAdapter = new ManagerAddAdapter();
        mGrid.setAdapter(mAdapter);

        mPresenter = new ManagerAddPresenter(this, new ManagerAddModel());
        //动态添加顶部货柜的按钮
        for (int i = 11;i >= 6;i--)
        {
            addTopButton(i);
        }
        for (int i = 1;i <= 5;i++)
        {
            addTopButton(i);
        }
        //默认选中第一个货柜
        if(mLlTop.getChildCount() > 0)
        {
            mBox = (Integer)mLlTop.getChildAt(0).getTag();
            mLlTop.getChildAt(0).setSelected(true);
        }
        //获取数据
        if(mBox > 0)
        {
            setBox(mBox);
        }
        return view;
    }

    private void addTopButton(final int pBox)
    {
        if(!DriverThread.getInstance().mRoadInfo.containsKey(pBox))
            return;
        final Button btn = new Button(getActivity());
        btn.setBackgroundResource(R.drawable.mgr_bt_box_selector);
        btn.setTag(pBox);
        btn.setTextColor(getResources().getColorStateList(R.color.color_box_selector));
        btn.setSelected(false);
        btn.setGravity(Gravity.CENTER);
        btn.setTextColor(Color.BLACK);
        btn.setTextSize(30);
        if(pBox == 11) {
            btn.setText(String.format(getResources().getString(R.string.mgr_add_box_yl), String.valueOf(pBox)));
        }
        else if(pBox >= 6 && pBox <= 9)
        {
            btn.setText(String.format(getResources().getString(R.string.mgr_add_box_sp), String.valueOf(pBox)));
        }
        else if(pBox >= 1 && pBox <= 5)
        {
            btn.setText(String.format(getResources().getString(R.string.mgr_add_box_pm), String.valueOf(pBox)));
        }
        btn.setOnClickListener(v -> {
            for(int i = 0;i < mLlTop.getChildCount();i++)
            {
                mLlTop.getChildAt(i).setSelected(false);
            }
            btn.setSelected(true);
            mBox = (Integer)btn.getTag();
            setBox(mBox);
        });
        mLlTop.addView(btn);
    }

    private void setBox(int pBox)
    {
        //mLogger.i("setBox:" + mBox);
        mList.clear();
        mList.addAll(mPresenter.getColumnDataByBox(pBox));
        //mLogger.i("list:" + mList.size());
        mAdapter.notifyDataSetChanged();
    }

    private void setImage(ImageView imageView, String imageName) {

        mImageLoader.displayImage("file://" + AppApplication.path + "/images/goods_image/" + imageName, imageView, options, mLoadingListener);
    }

    /**
     * 显示补货对话框
     * @param pColumn 货道号
     * @param pModel 货道模型
     */
    private void showDialog(final int pColumn, final String pColumnStr, final ColumnModel pModel) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = View.inflate(getActivity(), R.layout.dialog_manager_add, null);
        builder.setView(view);

        // 获取布局
        final TextView tv_dialog_title = view.findViewById(R.id.tv_dialog_title);
        final ImageView iv_image = view.findViewById(R.id.iv_image);
        final TextView tv_goods_name = view.findViewById(R.id.tv_goods_name);
        final TextView tv_goods_id = view.findViewById(R.id.tv_goods_id);
        final LongClickButton bt_minus_price = view.findViewById(R.id.bt_minus_price);
        final TextView tv_price_value = view.findViewById(R.id.tv_price_value);
        final LongClickButton bt_plus_price = view.findViewById(R.id.bt_plus_price);
        final Button bt_minus_max_stock = view.findViewById(R.id.bt_minus_max_stock);
        final TextView tv_max_stock_value = view.findViewById(R.id.tv_max_stock_value);
        final Button bt_plus_max_stock = view.findViewById(R.id.bt_plus_max_stock);
        final Button bt_minus_stock = view.findViewById(R.id.bt_minus_stock);
        final TextView tv_stock_value = view.findViewById(R.id.tv_stock_value);
        final Button bt_plus_stock = view.findViewById(R.id.bt_plus_stock);

        if(mBox >= 1 && mBox <= 5) //商品柜不能修改最大补货量
        {
            bt_minus_max_stock.setVisibility(View.INVISIBLE);
            bt_plus_max_stock.setVisibility(View.INVISIBLE);
        }
        else
        {
            bt_minus_max_stock.setVisibility(View.VISIBLE);
            bt_plus_max_stock.setVisibility(View.VISIBLE);
        }

        // 初始化变量
        tv_dialog_title.setText(String.format(getString(R.string.mgr_add_column), pColumnStr));
        setImage(iv_image, String.valueOf(pModel.goodsId) + "/0.png");
        String goodsName = "";
        for (GoodsModel goods: Configure.goodsList)
        {
            if(goods.getCode().equals(String.valueOf(pModel.goodsId)))
            {
                goodsName = goods.getName();
                break;
            }
        }
        tv_goods_name.setText(goodsName);
        tv_goods_id.setText(String.valueOf(pModel.goodsId));
        mGoodsPrice = pModel.price;
        String price = Tools.priceFormat(String.valueOf(mGoodsPrice));
        tv_price_value.setText(price);
        tv_max_stock_value.setText(String.valueOf(pModel.maxStock));
        tv_stock_value.setText(String.valueOf(pModel.num));

        bt_minus_price.setOnClickListener(view1 -> {
            int p = mGoodsPrice;
            p -= 10;
            if(p < 10)
            {
                p = 10;
            }
            mGoodsPrice = p;
            tv_price_value.setText(Tools.priceFormat(String.valueOf(mGoodsPrice)));
        });
        bt_minus_price.setLongClickRepeatListener(new LongClickButton.LongClickRepeatListener() {
            @Override
            public void repeatAction() {
                int p = mGoodsPrice;
                p -= 100;
                if(p < 10)
                {
                    p = 10;
                }
                mGoodsPrice = p;
                tv_price_value.setText(Tools.priceFormat(String.valueOf(mGoodsPrice)));
            }
        });
        bt_plus_price.setOnClickListener(view1 -> {
            int p = mGoodsPrice;
            p += 10;
            if(p > 655350)
            {
                p = 655350;
            }
            mGoodsPrice = p;
            tv_price_value.setText(Tools.priceFormat(String.valueOf(mGoodsPrice)));
        });
        bt_plus_price.setLongClickRepeatListener(new LongClickButton.LongClickRepeatListener() {
            @Override
            public void repeatAction() {
                int p = mGoodsPrice;
                p += 100;
                if(p > 655350)
                {
                    p = 655350;
                }
                mGoodsPrice = p;
                tv_price_value.setText(Tools.priceFormat(String.valueOf(mGoodsPrice)));
            }
        });
        bt_minus_max_stock.setOnClickListener(view1 -> {
            String price1 = tv_max_stock_value.getText().toString();
            int p;
            try
            {
                p = Integer.parseInt(price1);
            }
            catch(NumberFormatException e)
            {
                return;
            }
            p -= 1;
            if(p < 1)
            {
                p = 1;
            }
            tv_max_stock_value.setText(String.valueOf(p));
        });
        bt_plus_max_stock.setOnClickListener(view1 -> {
            String price1 = tv_max_stock_value.getText().toString();
            int p;
            try
            {
                p = Integer.parseInt(price1);
            }
            catch(NumberFormatException e)
            {
                return;
            }
            p += 1;
            if(p > 99)
            {
                p = 99;
            }
            tv_max_stock_value.setText(String.valueOf(p));
        });
        bt_minus_stock.setOnClickListener(view1 -> {
            String price1 = tv_stock_value.getText().toString();
            int p;
            try
            {
                p = Integer.parseInt(price1);
            }
            catch(NumberFormatException e)
            {
                return;
            }
            p -= 1;
            if(p < 0)
            {
                p = 0;
            }
            tv_stock_value.setText(String.valueOf(p));
        });
        bt_plus_stock.setOnClickListener(view1 -> {
            //先拿到最大补货量
            String maxstr = tv_max_stock_value.getText().toString();
            int max;
            try
            {
                max = Integer.parseInt(maxstr);
            }
            catch(NumberFormatException e)
            {
                return;
            }

            String price1 = tv_stock_value.getText().toString();
            int p;
            try
            {
                p = Integer.parseInt(price1);
            }
            catch(NumberFormatException e)
            {
                return;
            }
            p += 1;
            if(p > max) //库存不能超过最大补货量
            {
                p = max;
            }
            tv_stock_value.setText(String.valueOf(p));
        });
        iv_image.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                showChangeGoodsImageDialog(iv_image, tv_goods_name, tv_goods_id);
            }
        });

        builder.setPositiveButton(R.string.ok, (dialog, which) -> {
            mPresenter.setColumnData(mBox, pColumn, tv_goods_id.getText().toString(), mGoodsPrice, Integer.parseInt(tv_max_stock_value.getText().toString()), Integer.parseInt(tv_stock_value.getText().toString()));
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
        builder.show();
    }

    private void showChangeGoodsImageDialog(final ImageView pImageView, final TextView pTextViewName, final TextView pTextViewId)
    {
        View view = View.inflate(getActivity(), R.layout.dialog_select_goods_image, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.mgr_add_dialog_select_goods_title).setCancelable(false).setView(view)
                .setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
        final Dialog dialog = builder.create();
        ListView listView = view.findViewById(R.id.lv_goods_image);
        GoodsImageListAdapter goodsImageListAdapter = new GoodsImageListAdapter(pTextViewId.getText().toString());
        listView.setAdapter(goodsImageListAdapter);
        listView.setOnItemClickListener((parent, view1, position, id) -> {
            if (Configure.goodsList != null) {
                final GoodsModel item = Configure.goodsList.get(position);
                setImage(pImageView, String.valueOf(item.getCode()) + "/0.png");
                // 修改商品名称和ID
                pTextViewName.setText(item.getName());
                pTextViewId.setText(String.valueOf(item.getCode()));
            }
            dialog.dismiss();
        });
        dialog.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_add_one:
                mPresenter.addSingleBox(mBox);
                break;
            case R.id.bt_add_all:
                mPresenter.addAllBox(mBox);
                break;
            case R.id.bt_import:
                mPresenter.importData();
                break;
            case R.id.bt_export:
                mPresenter.exportData();
                break;
            case R.id.bt_back:
                goToFragment(ManagerActivity.FRAGMENT_MENU, null);
                break;
        }
    }

    @Override
    public void showProgressBar() {
        if(mProgressDialog == null)
        {
            mProgressDialog = new ProgressDialog(getActivity());
        }
        if(mProgressDialog.isShowing())
            return;
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(getResources().getString(R.string.loading));
        mProgressDialog.show();
    }

    @Override
    public void hideProgressBar() {
        if(mProgressDialog != null)
        {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void progress(int pProgress) {
        if(mProgressDialog != null)
        {
            mProgressDialog.setProgress(pProgress);
        }
    }

    @Override
    public void showMessage(int pMessage) {
        switch (pMessage)
        {
            case IManagerAddView.OPT_SUCCESS:
                Toast.makeText(getActivity(), R.string.opt_success, Toast.LENGTH_SHORT).show();
                break;
            case IManagerAddView.OPT_FAILED:
                Toast.makeText(getActivity(), R.string.opt_failed, Toast.LENGTH_SHORT).show();
                break;
            case IManagerAddView.OPT_NO_UDISK:
                Toast.makeText(getActivity(), R.string.opt_no_udisk, Toast.LENGTH_SHORT).show();
                break;
            case IManagerAddView.OPT_NO_FILE:
                Toast.makeText(getActivity(), R.string.opt_no_file, Toast.LENGTH_SHORT).show();
                break;
            case IManagerAddView.OPT_COPY_ERROR:
                Toast.makeText(getActivity(), R.string.opt_copy_error, Toast.LENGTH_SHORT).show();
                break;
        }
        setBox(mBox);
    }

    class ManagerAddAdapter extends BaseAdapter {

        ViewHolder holder;

        public ManagerAddAdapter()
        {
            super();
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if(convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.item_manager_add_list, null);
                holder = new ViewHolder();
                holder.tv_id = convertView.findViewById(R.id.tv_id);
                holder.tv_id_value = convertView.findViewById(R.id.tv_id_value);
                holder.tv_max_stock = convertView.findViewById(R.id.tv_max_stock);
                holder.tv_max_stock_value = convertView.findViewById(R.id.tv_max_stock_value);
                holder.tv_stock = convertView.findViewById(R.id.tv_stock);
                holder.tv_stock_value = convertView.findViewById(R.id.tv_stock_value);
                holder.tv_price = convertView.findViewById(R.id.tv_price);
                holder.tv_price_value = convertView.findViewById(R.id.tv_price_value);
                holder.tv_goods = convertView.findViewById(R.id.tv_goods);
                holder.tv_goods_value = convertView.findViewById(R.id.tv_goods_value);
                holder.ll_image = convertView.findViewById(R.id.ll_image);
                holder.iv_image = convertView.findViewById(R.id.iv_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            //设置货道数据
            final ColumnModel model = mList.get(position);
            String info = Configure.convertColumn(mBox, position + 1);
            holder.tv_max_stock_value.setText(String.valueOf(model.maxStock));
            if(mBox == DriverThread.BOX_YL) //饮料机只显示是否有货
            {
                holder.tv_stock_value.setText(model.isBreak ? getResources().getString(R.string.mgr_add_stock_no) : getResources().getString(R.string.mgr_add_stock_yes));
                info = info.substring(2);
                holder.tv_id_value.setText(info);
            }
            else
            {
                holder.tv_stock_value.setText(String.valueOf(model.num));
                info = info.substring(1);
                holder.tv_id_value.setText(info);
            }
            final String columnStr = info;
            holder.tv_price_value.setText(Tools.priceFormat(String.valueOf(model.price)));
            holder.tv_goods_value.setText(String.valueOf(model.goodsId));
            setImage(holder.iv_image, String.valueOf(model.goodsId) + "/0.png");
            if(model.goodsId == DriverThread.COLUMN_DISABLED) //禁用的货道显示不同的背景颜色
            {
                holder.tv_id.setBackgroundColor(getResources().getColor(R.color.color_column_gray));
                holder.tv_id_value.setBackgroundResource(R.drawable.mgr_column_gray_bg);
                holder.tv_max_stock.setBackgroundColor(getResources().getColor(R.color.color_column_gray));
                holder.tv_max_stock_value.setBackgroundResource(R.drawable.mgr_column_gray_bg);
                holder.tv_stock.setBackgroundColor(getResources().getColor(R.color.color_column_gray));
                holder.tv_stock_value.setBackgroundResource(R.drawable.mgr_column_gray_bg);
                holder.tv_price.setBackgroundColor(getResources().getColor(R.color.color_column_gray));
                holder.tv_price_value.setBackgroundResource(R.drawable.mgr_column_gray_bg);
                holder.tv_goods.setBackgroundColor(getResources().getColor(R.color.color_column_gray));
                holder.tv_goods_value.setBackgroundResource(R.drawable.mgr_column_gray_bg);
                holder.ll_image.setBackgroundResource(R.drawable.mgr_goods_gray_bg);
            }
            else
            {
                holder.tv_id.setBackgroundColor(getResources().getColor(R.color.color_column_normal));
                holder.tv_id_value.setBackgroundResource(R.drawable.mgr_column_white_bg);
                holder.tv_max_stock.setBackgroundColor(getResources().getColor(R.color.color_column_normal));
                holder.tv_max_stock_value.setBackgroundResource(R.drawable.mgr_column_white_bg);
                holder.tv_stock.setBackgroundColor(getResources().getColor(R.color.color_column_normal));
                holder.tv_stock_value.setBackgroundResource(R.drawable.mgr_column_white_bg);
                holder.tv_price.setBackgroundColor(getResources().getColor(R.color.color_column_normal));
                holder.tv_price_value.setBackgroundResource(R.drawable.mgr_column_white_bg);
                holder.tv_goods.setBackgroundColor(getResources().getColor(R.color.color_column_normal));
                holder.tv_goods_value.setBackgroundResource(R.drawable.mgr_column_white_bg);
                holder.ll_image.setBackgroundResource(R.drawable.mgr_goods_white_bg);
            }
            convertView.setOnClickListener(v -> {
                if(model.goodsId == DriverThread.COLUMN_DISABLED) //被禁用的货道无法进行操作
                {
                    Toast.makeText(getActivity(), R.string.mgr_add_column_disabled, Toast.LENGTH_SHORT).show();
                }
                else
                {
                    //显示补货对话框
                    showDialog(position + 1, columnStr, model);
                }
            });
            return convertView;
        }

        class ViewHolder
        {
            TextView tv_id;
            TextView tv_id_value;
            TextView tv_max_stock;
            TextView tv_max_stock_value;
            TextView tv_stock;
            TextView tv_stock_value;
            TextView tv_price;
            TextView tv_price_value;
            TextView tv_goods;
            TextView tv_goods_value;
            LinearLayout ll_image;
            ImageView iv_image;
        }
    }

    class GoodsImageListAdapter extends BaseAdapter {
        private String mCode = "";

        public GoodsImageListAdapter(String code) {
            this.mCode = code;
        }

        @Override
        public int getCount() {
            if (Configure.goodsList == null) {
                return 0;
            }
            return Configure.goodsList.size();
        }

        @Override
        public Object getItem(int position) {
            if (Configure.goodsList == null) {
                return null;
            }
            return Configure.goodsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            GoodsImageListHolder mHolder;
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.item_goods_list, null);
                mHolder = new GoodsImageListHolder();
                mHolder.image = convertView.findViewById(R.id.iv_goods_image);
                mHolder.name = convertView.findViewById(R.id.tv_goods_name);
                mHolder.code = convertView.findViewById(R.id.tv_goods_code);
                mHolder.isCurrent = convertView.findViewById(R.id.cb_current);
                convertView.setTag(mHolder);
            } else {
                mHolder = (GoodsImageListHolder) convertView.getTag();
            }
            final GoodsModel item = Configure.goodsList.get(position);
            setImage(mHolder.image, String.valueOf(item.getCode()) + "/0.png");

            mHolder.name.setText(item.getName());
            mHolder.code.setText(String.valueOf(item.getCode()));
            if (mCode.equals(String.valueOf(item.getCode()))) {
                mHolder.isCurrent.setChecked(true);
                mHolder.isCurrent.setVisibility(View.VISIBLE);
            } else {
                mHolder.isCurrent.setChecked(false);
                mHolder.isCurrent.setVisibility(View.INVISIBLE);
            }
            return convertView;
        }

        class GoodsImageListHolder {
            ImageView image;
            TextView name;
            TextView code;
            CheckBox isCurrent;
        }
    }
}
